﻿/***************************************************
 * 模块名称：获取真实ip中间件
 * 功能概述：获取真实ip中间件
 * 创建人：李洪亮
 * 创建时间：2019-06-12
 * 修改人：
 * 修改时间：
 * 修改描述：
 *************************************************/
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace MICZ.CodeBuilder.Commons.Comn
{
    /// <summary>
    /// 获取真实ip中间件
    /// </summary>
    public class RealIpMiddleware
    {
        private readonly RequestDelegate _next;

        public RealIpMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext context)
        {
            var headers = context.Request.Headers;
            if (headers.ContainsKey("X-Forwarded-For"))
            {
                context.Connection.RemoteIpAddress = IPAddress.Parse(headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0]);
            }
            return _next(context);
        }
    }
}
